package com.example.day27_videocall;

import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;

/**
 * Description:socket通讯 客户端
 * Created by Gdu on 2021/1/5 11:30.
 */

public class SocketLive {
    private static final String TAG = "SocketLive";
    private SocketCallback socketCallback;
    private String uriPath = "ws://192.168.18.52:40002";
    private MyWebSocketClient myWebSocketClient;

    public SocketLive(SocketCallback socketCallback) {
        this.socketCallback = socketCallback;
    }

    public void start(){
        try {
            URI uri = new URI(uriPath);
            myWebSocketClient = new MyWebSocketClient(uri);
            myWebSocketClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendData(byte[] bytes){
        if (myWebSocketClient != null && (myWebSocketClient.isOpen())) {
            myWebSocketClient.send(bytes);
        }
    }

    private class MyWebSocketClient extends WebSocketClient{
        public MyWebSocketClient(URI serverUri) {
            super(serverUri);
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            Log.i("MyWebSocketClient", "onOpen======");
        }

        @Override
        public void onMessage(String message) { }

        @Override
        public void onMessage(ByteBuffer bytes) {
            Log.i("MyWebSocketClient", "onMessage======" + bytes.remaining());
            byte[] buf = new byte[bytes.remaining()];
            bytes.get(buf);
            socketCallback.CallBack(buf);
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            Log.i("MyWebSocketClient", "onClose======" + reason);
        }

        @Override
        public void onError(Exception ex) {
            Log.i("MyWebSocketClient", "onError======" + ex.toString());
        }
    }

    public interface SocketCallback{
        void CallBack(byte[] data);

    }

}
